import CesiumApp from '../CesiumApp';
import VGE from '../../../VGE';

export function recordChangedView(viewer, iCesium) {
	viewer.viewIndex = 0;
	let wheelClock = null;
	let moveWheel1 = true;
	let moveWheel2 = false;
	let before = null;
	let after = null;
	let drag = false;

	const handler = new iCesium.ScreenSpaceEventHandler(viewer.scene.canvas);
	[
		iCesium.ScreenSpaceEventType.LEFT_DOWN,
		iCesium.ScreenSpaceEventType.MIDDLE_DOWN,
		iCesium.ScreenSpaceEventType.RIGHT_DOWN
	].forEach((item) => {
		handler.setInputAction(async (_) => {
			drag = false;
			before = await CesiumApp.camera.getCameraParams();
		}, item);
	});
	[iCesium.ScreenSpaceEventType.MOUSE_MOVE].forEach((item) => {
		handler.setInputAction(async (_) => {
			drag = true;
		}, item);
	});
	[
		iCesium.ScreenSpaceEventType.LEFT_UP,
		iCesium.ScreenSpaceEventType.MIDDLE_UP,
		iCesium.ScreenSpaceEventType.RIGHT_UP
	].forEach((item) => {
		handler.setInputAction(async (_) => {
			after = await CesiumApp.camera.getCameraParams();
			drag && saveViewUndo(before, after);
		}, item);
	});

	const dom = viewer._container;
	dom.onmousewheel = async () => {
		if (moveWheel1) {
			moveWheel1 = false;
			moveWheel2 = true;
			before = await CesiumApp.camera.getCameraParams();
			// 这里写开始滚动时调用的方法
			wheelClock = setTimeout(stopWheel, 200);
		} else {
			clearTimeout(wheelClock);
			wheelClock = setTimeout(stopWheel, 150);
		}
		async function stopWheel() {
			if (moveWheel2) {
				moveWheel1 = true;
				moveWheel2 = false;
				after = await CesiumApp.camera.getCameraParams();
				// 这里写停止时调用的方法
				saveViewUndo(before, after);
			}
		}
	};
}

export function saveViewUndo(before, after) {
	if (!VGE.util.validateCameraParams(before) || !VGE.util.validateCameraParams(after)) return;

	if (JSON.stringify(before) !== JSON.stringify(after)) {
		const viewer = CesiumApp.viewer;
		const backStack = viewer.backStack;

		if (!viewer._currentBaseline) {
			viewer._currentBaseline = before;
		}

		if (backStack.length >= 5) backStack.shift();

		viewer.backStack.push(viewer._currentBaseline);
		viewer.forwardStack.length = 0;

		viewer._currentBaseline = after;
	}
}
